﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tamir.IPLib;
using Tamir.IPLib.Packets;

namespace ConsoleApplication1
{
    public class Program
    {
        public PcapDeviceList devices;

        public static void Main(string[] args)
        {
            new Program();
        }

        public Program()
        {
            ObtainDevices();
            ShowPackets();
        }

        public void ObtainDevices()
        {
            /* Retrieve the device list */
            devices = SharpPcap.GetAllDevices();

            /*If no device exists, print error */
            if (devices.Count < 1)
            {
                Console.WriteLine("No device found on this machine");
                return;
            }

            int i = 0;

            /* Scan the list printing every entry */
            foreach (PcapDevice dev in devices)
            {
                /* Description */
                Console.WriteLine("{0}) {1}", i, dev.PcapDescription);
                Console.WriteLine();
                /* Name */
                Console.WriteLine("\tName:\t{0}", dev.PcapName);
                /* IP Address */
                Console.WriteLine("\tIP Address: \t\t{0}", dev.PcapIpAddress);
                /* Is Loopback */
                Console.WriteLine("\tLoopback: \t\t{0}", dev.PcapLoopback);

                Console.WriteLine();
                i++;
            }
            
        }

        public void ShowPackets()
        {
            foreach (PcapDevice device in devices)
            {
                device.PcapOpen(true, 10000);
				device.PcapOnPacketArrival += new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);
                Console.WriteLine();
                Console.WriteLine("-- Listenning on {0}...",
                device.PcapDescription);
                Packet packet = null;
            	

                //Keep capture packets using PcapGetNextPacket()
                while ((packet = device.PcapGetNextPacket()) != null)
                {

                }
                //Close the pcap device
                device.PcapClose();
                Console.WriteLine("-- Capture stopped, device closed.");
                
            }
            Console.Read();
        }

		void device_PcapOnPacketArrival(object sender, Packet packet)
		{
			TCPPacket tcpPacket = packet as TCPPacket;

			if (tcpPacket != null)
			{
				// Prints the time and length of each received packet
				DateTime time = tcpPacket.PcapHeader.Date;

				int len = packet.PcapHeader.PacketLength;
				string sourceAddress = tcpPacket.SourceAddress;
				string destinationAddress = tcpPacket.DestinationAddress;
				Console.WriteLine("{0:hh:mm:ss}, Source={1}, Destination={2}, Len={3}", time, sourceAddress, destinationAddress, len);
			}
		}
    }
}
